package com.application.api;

import com.application.api.entity.ResultEntity;
import com.application.common.utils.ImageUtils;
import com.application.image.Image;
import com.application.image.ImageService;
import com.jfinal.kit.FileKit;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;
import com.platform.annotation.Controller;
import com.platform.constant.ConstantInit;
import com.platform.mvc.base.BaseController;
import com.platform.tools.ToolString;
import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * 图片上传
 */
@Controller({"/api/image", "/api/upload"})
public class ImageApiController extends BaseController {

	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(ImageApiController.class);

	private String filePath = "/files/upload/";

	private static String filesDir = PropKit.get("files.dir");

    ImageService imgService;

	/**
	 * @title 图片上传处理:/shop/api/image/{module}
     * @param file|头像|文件|必填
     * @param {module}|可选值: 头像：user；
     *              |String|必填
     * @param authmark|XJXQUMzWGxO
     *               |固定值放入header|必填
	 */
	public void index() {
        String m = getPara();

        if(m == null) {
            m = "other";
        }
        switch (m){
            case "user":
                filePath += "user/" + super.getCUserIds();
                break;
            default:
                filePath += m;

        }
        List<UploadFile> files = getFiles(filePath, PropKit.getInt(ConstantInit.config_maxPostSize_key), ToolString
                .encoding);
/*
		String tmp = filePath + "temp/" + ToolDateTime.format(new Date(System.currentTimeMillis()), "yyyyMMdd");


		List<UploadFile> files = getFiles(tmp, PropKit.getInt(ConstantInit.config_maxPostSize_key), ToolString
				.encoding);

        String m = getPara("module");
        switch (m){
            case "user":
                filePath += "user/" + super.getCUserIds();
            default:
                filePath += m;

        }*/

        List<Image> list = imgService.upload(getCUserIds(), filePath, files);

		renderJson(new ResultEntity(list));
	}

    /**
     * 上传Base64文件
     */
    public void uploadBase64() {
        String m = getPara("module", "base64");
        String base64 = getPara("base64");
        String fileName = filePath + m + "/" + UUID.randomUUID().toString() + ".jpg";
        String filePath = filesDir + fileName;
        ImageUtils.convertBase64ToImage(base64, filePath);
        success(fileName);
    }



	/**
	 * 单张图片删除,/shop/api/image/delete/{imageId}
	 * 只能由图片创建者或者管理员用户类型人员删除
	 */
	public void deleteSingle() {

		Image image = Image.dao.findById(getPara());

	/*	String cUserType = getUserType();
		if(!Constant.AdminUser.equals(cUserType) && !Constant.SuperAdmin.equals(cUserType)){
			if(!image.get(Image.column_createUserId).equals(getCUserIds())){
				renderJson(new ResultEntity(HttpStatus.SC_FORBIDDEN, "请联系管理员进行删除"));
				return;
			}
		}*/

		if(image.delete()){
			renderJson(new ResultEntity(HttpStatus.SC_OK, "图片删除成功"));
			return;
		}

		renderJson(new ResultEntity(HttpStatus.SC_NOT_FOUND, "图片不存在或已被删除"));
	}

	/**
	 * /shop/api/image/delete/
	 * 参数ids：imageIds；多个以逗号分隔
	 */
    @Deprecated
	public void delete() {
		String imageIds = getPara() == null ? ids : getPara();
        imgService.baseDelete("image", imageIds);

		for (String imageId : imageIds.split(",")) {
			//删除物理文件
			Image image = Image.dao.findById(imageId);
			if (image != null) {
				File file = new File(image.getFilePath());
				if (file.exists()) {
					FileKit.delete(file);
				}
			}
		}
		renderJson(new ResultEntity(HttpStatus.SC_OK, "图片删除成功"));
	}
	
}
